home *** CD-ROM | disk | FTP | other *** search
/ Personal Computer World 2008 February / PCWFEB08.iso / Software / Freeware / Miro 1.0 / Miro_Installer.exe / xulrunner / python / xpcom / server / policy.py < prev   
Encoding:
Python Source  |  2007-11-12  |  15.7 KB  |  354 lines

  1. # ***** BEGIN LICENSE BLOCK *****
  2. # Version: MPL 1.1/GPL 2.0/LGPL 2.1
  3. #
  4. # The contents of this file are subject to the Mozilla Public License Version
  5. # 1.1 (the "License"); you may not use this file except in compliance with
  6. # the License. You may obtain a copy of the License at
  7. # http://www.mozilla.org/MPL/
  8. #
  9. # Software distributed under the License is distributed on an "AS IS" basis,
  10. # WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
  11. # for the specific language governing rights and limitations under the
  12. # License.
  13. #
  14. # The Original Code is Python XPCOM language bindings.
  15. #
  16. # The Initial Developer of the Original Code is
  17. # ActiveState Tool Corp.
  18. # Portions created by the Initial Developer are Copyright (C) 2001
  19. # the Initial Developer. All Rights Reserved.
  20. #
  21. # Contributor(s):
  22. #  Mark Hammond <mhammond@skippinet.com.au> (original author)
  23. #
  24. # Alternatively, the contents of this file may be used under the terms of
  25. # either the GNU General Public License Version 2 or later (the "GPL"), or
  26. # the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
  27. # in which case the provisions of the GPL or the LGPL are applicable instead
  28. # of those above. If you wish to allow use of your version of this file only
  29. # under the terms of either the GPL or the LGPL, and not to allow others to
  30. # use your version of this file under the terms of the MPL, indicate your
  31. # decision by deleting the provisions above and replace them with the notice
  32. # and other provisions required by the GPL or the LGPL. If you do not delete
  33. # the provisions above, a recipient may use your version of this file under
  34. # the terms of any one of the MPL, the GPL or the LGPL.
  35. #
  36. # ***** END LICENSE BLOCK *****
  37.  
  38. from xpcom import xpcom_consts, _xpcom, client, nsError, ServerException, COMException
  39. import xpcom
  40. import traceback
  41. import xpcom.server
  42. import operator
  43. import types
  44.  
  45. IID_nsISupports = _xpcom.IID_nsISupports
  46. IID_nsIVariant = _xpcom.IID_nsIVariant
  47. XPT_MD_IS_GETTER = xpcom_consts.XPT_MD_IS_GETTER
  48. XPT_MD_IS_SETTER = xpcom_consts.XPT_MD_IS_SETTER
  49.  
  50. VARIANT_INT_TYPES = xpcom_consts.VTYPE_INT8, xpcom_consts.VTYPE_INT16, xpcom_consts.VTYPE_INT32, \
  51.                     xpcom_consts.VTYPE_UINT8, xpcom_consts.VTYPE_UINT16, xpcom_consts.VTYPE_INT32
  52. VARIANT_LONG_TYPES = xpcom_consts.VTYPE_INT64, xpcom_consts.VTYPE_UINT64
  53. VARIANT_FLOAT_TYPES = xpcom_consts.VTYPE_FLOAT, xpcom_consts.VTYPE_DOUBLE
  54. VARIANT_STRING_TYPES = xpcom_consts.VTYPE_CHAR, xpcom_consts.VTYPE_CHAR_STR, xpcom_consts.VTYPE_STRING_SIZE_IS, \
  55.                        xpcom_consts.VTYPE_CSTRING
  56. VARIANT_UNICODE_TYPES = xpcom_consts.VTYPE_WCHAR, xpcom_consts.VTYPE_DOMSTRING, xpcom_consts.VTYPE_WSTRING_SIZE_IS, \
  57.                         xpcom_consts.VTYPE_ASTRING 
  58.  
  59. _supports_primitives_map_ = {} # Filled on first use.
  60.  
  61. _interface_sequence_types_ = types.TupleType, types.ListType
  62. _string_types_ = types.StringType, types.UnicodeType
  63. XPTI_GetInterfaceInfoManager = _xpcom.XPTI_GetInterfaceInfoManager
  64.  
  65. def _GetNominatedInterfaces(obj):
  66.     ret = getattr(obj, "_com_interfaces_", None)
  67.     if ret is None: return None
  68.     # See if the user only gave one.
  69.     if type(ret) not in _interface_sequence_types_:
  70.         ret = [ret]
  71.     real_ret = []
  72.     # For each interface, walk to the root of the interface tree.
  73.     iim = XPTI_GetInterfaceInfoManager()
  74.     for interface in ret:
  75.         # Allow interface name or IID.
  76.         interface_info = None
  77.         if type(interface) in _string_types_:
  78.             try:
  79.                 interface_info = iim.GetInfoForName(interface)
  80.             except COMException:
  81.                 pass
  82.         if interface_info is None:
  83.             # Allow a real IID
  84.             interface_info = iim.GetInfoForIID(interface)
  85.         real_ret.append(interface_info.GetIID())
  86.         parent = interface_info.GetParent()
  87.         while parent is not None:
  88.             parent_iid = parent.GetIID()
  89.             if parent_iid == IID_nsISupports:
  90.                 break
  91.             real_ret.append(parent_iid)
  92.             parent = parent.GetParent()
  93.     return real_ret
  94.  
  95. ##
  96. ## ClassInfo support
  97. ##
  98. ## We cache class infos by class
  99. class_info_cache = {}
  100.  
  101. def GetClassInfoForObject(ob):
  102.     if xpcom.server.tracer_unwrap is not None:
  103.         ob = xpcom.server.tracer_unwrap(ob)
  104.     klass = ob.__class__
  105.     ci = class_info_cache.get(klass)
  106.     if ci is None:
  107.         ci = DefaultClassInfo(klass)
  108.         ci = xpcom.server.WrapObject(ci, _xpcom.IID_nsIClassInfo, bWrapClient = 0)
  109.         class_info_cache[klass] = ci
  110.     return ci
  111.  
  112. class DefaultClassInfo:
  113.     _com_interfaces_ = _xpcom.IID_nsIClassInfo
  114.     def __init__(self, klass):
  115.         self.klass = klass
  116.         self.contractID = getattr(klass, "_reg_contractid_", None)
  117.         self.classDescription = getattr(klass, "_reg_desc_", None)
  118.         self.classID = getattr(klass, "_reg_clsid_", None)
  119.         self.implementationLanguage = 3 # Python - avoid lookups just for this
  120.         self.flags = 0 # what to do here??
  121.         self.interfaces = None
  122.  
  123.     def get_classID(self):
  124.         if self.classID is None:
  125.             raise ServerException(nsError.NS_ERROR_NOT_IMPLEMENTED, "Class '%r' has no class ID" % (self.klass,))
  126.         return self.classID
  127.  
  128.     def getInterfaces(self):
  129.         if self.interfaces is None:
  130.             self.interfaces = _GetNominatedInterfaces(self.klass)
  131.         return self.interfaces
  132.  
  133.     def getHelperForLanguage(self, language):
  134.         return None # Not sure what to do here.
  135.  
  136. class DefaultPolicy:
  137.     def __init__(self, instance, iid):
  138.         self._obj_ = instance
  139.         self._nominated_interfaces_ = ni = _GetNominatedInterfaces(instance)
  140.         self._iid_ = iid
  141.         if ni is None:
  142.             raise ValueError, "The object '%r' can not be used as a COM object" % (instance,)
  143.         # This is really only a check for the user
  144.         if __debug__:
  145.             if iid != IID_nsISupports and iid not in ni:
  146.                 # The object may delegate QI.
  147.                 delegate_qi = getattr(instance, "_query_interface_", None)
  148.                 # Perform the actual QI and throw away the result - the _real_
  149.                 # QI performed by the framework will set things right!
  150.                 if delegate_qi is None or not delegate_qi(iid):
  151.                     raise ServerException(nsError.NS_ERROR_NO_INTERFACE)
  152.         # Stuff for the magic interface conversion.
  153.         self._interface_info_ = None
  154.         self._interface_iid_map_ = {} # Cache - Indexed by (method_index, param_index)
  155.  
  156.     def _QueryInterface_(self, com_object, iid):
  157.         # Framework allows us to return a single boolean integer,
  158.         # or a COM object.
  159.         if iid in self._nominated_interfaces_:
  160.             # We return the underlying object re-wrapped
  161.             # in a new gateway - which is desirable, as one gateway should only support
  162.             # one interface (this wont affect the users of this policy - we can have as many
  163.             # gateways as we like pointing to the same Python objects - the users never
  164.             # see what object the call came in from.
  165.             # NOTE: We could have simply returned the instance and let the framework
  166.             # do the auto-wrap for us - but this way we prevent a round-trip back into Python
  167.             # code just for the autowrap.
  168.             return xpcom.server.WrapObject(self._obj_, iid, bWrapClient = 0)
  169.  
  170.         # Always support nsIClassInfo 
  171.         if iid == _xpcom.IID_nsIClassInfo:
  172.             return GetClassInfoForObject(self._obj_)
  173.  
  174.         # See if the instance has a QI
  175.         # use lower-case "_query_interface_" as win32com does, and it doesnt really matter.
  176.         delegate = getattr(self._obj_, "_query_interface_", None)
  177.         if delegate is not None:
  178.             # The COM object itself doesnt get passed to the child
  179.             # (again, as win32com doesnt).  It is rarely needed
  180.             # (in win32com, we dont even pass it to the policy, although we have identified
  181.             # one place where we should - for marshalling - so I figured I may as well pass it
  182.             # to the policy layer here, but no all the way down to the object.
  183.             return delegate(iid)
  184.         # Finally see if we are being queried for one of the "nsISupports primitives"
  185.         if not _supports_primitives_map_:
  186.             iim = _xpcom.XPTI_GetInterfaceInfoManager()
  187.             for (iid_name, attr, cvt) in _supports_primitives_data_:
  188.                 special_iid = iim.GetInfoForName(iid_name).GetIID()
  189.                 _supports_primitives_map_[special_iid] = (attr, cvt)
  190.         attr, cvt = _supports_primitives_map_.get(iid, (None,None))
  191.         if attr is not None and hasattr(self._obj_, attr):
  192.             return xpcom.server.WrapObject(SupportsPrimitive(iid, self._obj_, attr, cvt), iid, bWrapClient = 0)
  193.         # Out of clever things to try!
  194.         return None # We dont support this IID.
  195.  
  196.     def _MakeInterfaceParam_(self, interface, iid, method_index, mi, param_index):
  197.         # Wrap a "raw" interface object in a nice object.  The result of this
  198.         # function will be passed to one of the gateway methods.
  199.         if iid is None:
  200.             # look up the interface info - this will be true for all xpcom called interfaces.
  201.             if self._interface_info_ is None:
  202.                 import xpcom.xpt
  203.                 self._interface_info_ = xpcom.xpt.Interface( self._iid_ )
  204.             iid = self._interface_iid_map_.get( (method_index, param_index))
  205.             if iid is None:
  206.                 iid = self._interface_info_.GetIIDForParam(method_index, param_index)
  207.                 self._interface_iid_map_[(method_index, param_index)] = iid
  208.         # handle nsIVariant
  209.         if iid == IID_nsIVariant:
  210.             interface = interface.QueryInterface(iid)
  211.             dt = interface.dataType
  212.             if dt in VARIANT_INT_TYPES:
  213.                 return interface.getAsInt32()
  214.             if dt in VARIANT_LONG_TYPES:
  215.                 return interface.getAsInt64()
  216.             if dt in VARIANT_FLOAT_TYPES:
  217.                 return interface.getAsFloat()
  218.             if dt in VARIANT_STRING_TYPES:
  219.                 return interface.getAsStringWithSize()
  220.             if dt in VARIANT_UNICODE_TYPES:
  221.                 return interface.getAsWStringWithSize()
  222.             if dt == xpcom_consts.VTYPE_BOOL:
  223.                 return interface.getAsBool()
  224.             if dt == xpcom_consts.VTYPE_INTERFACE:
  225.                 return interface.getAsISupports()
  226.             if dt == xpcom_consts.VTYPE_INTERFACE_IS:
  227.                 return interface.getAsInterface()
  228.             if dt == xpcom_consts.VTYPE_EMPTY or dt == xpcom_consts.VTYPE_VOID:
  229.                 return None
  230.             if dt == xpcom_consts.VTYPE_ARRAY:
  231.                 return interface.getAsArray()
  232.             if dt == xpcom_consts.VTYPE_EMPTY_ARRAY:
  233.                 return []
  234.             if dt == xpcom_consts.VTYPE_ID:
  235.                 return interface.getAsID()
  236.             # all else fails...
  237.             print "Warning: nsIVariant type %d not supported - returning a string" % (dt,)
  238.             try:
  239.                 return interface.getAsString()
  240.             except COMException:
  241.                 print "Error: failed to get Variant as a string - returning variant object"
  242.                 traceback.print_exc()
  243.                 return interface
  244.             
  245.         return client.Component(interface, iid)
  246.     
  247.     def _CallMethod_(self, com_object, index, info, params):
  248.         #print "_CallMethod_", index, info, params
  249.         flags, name, param_descs, ret = info
  250.         assert ret[1][0] == xpcom_consts.TD_UINT32, "Expected an nsresult (%s)" % (ret,)
  251.         if XPT_MD_IS_GETTER(flags):
  252.             # Look for a function of that name
  253.             func = getattr(self._obj_, "get_" + name, None)
  254.             if func is None:
  255.                 assert len(param_descs)==1 and len(params)==0, "Can only handle a single [out] arg for a default getter"
  256.                 ret = getattr(self._obj_, name) # Let attribute error go here!
  257.             else:
  258.                 ret = func(*params)
  259.             return 0, ret
  260.         elif XPT_MD_IS_SETTER(flags):
  261.             # Look for a function of that name
  262.             func = getattr(self._obj_, "set_" + name, None)
  263.             if func is None:
  264.                 assert len(param_descs)==1 and len(params)==1, "Can only handle a single [in] arg for a default setter"
  265.                 setattr(self._obj_, name, params[0]) # Let attribute error go here!
  266.             else:
  267.                 func(*params)
  268.             return 0
  269.         else:
  270.             # A regular method.
  271.             func = getattr(self._obj_, name)
  272.             return 0, func(*params)
  273.  
  274.     def _doHandleException(self, func_name, exc_info):
  275.         exc_val = exc_info[1]
  276.         is_server_exception = isinstance(exc_val, ServerException)
  277.         if is_server_exception:
  278.             if xpcom.verbose:
  279.                 print "** Information:  '%s' raised COM Exception %s" % (func_name, exc_val)
  280.                 traceback.print_exception(exc_info[0], exc_val, exc_info[2])
  281.                 print "** Returning nsresult from existing exception", exc_val
  282.             return exc_val.errno
  283.         # Unhandled exception - always print a warning.
  284.         print "** Unhandled exception calling '%s'" % (func_name,)
  285.         traceback.print_exception(exc_info[0], exc_val, exc_info[2])
  286.         print "** Returning nsresult of NS_ERROR_FAILURE"
  287.         return nsError.NS_ERROR_FAILURE
  288.  
  289.  
  290.     # Called whenever an unhandled Python exception is detected as a result
  291.     # of _CallMethod_ - this exception may have been raised during the _CallMethod_
  292.     # invocation, or after its return, but when unpacking the results
  293.     # eg, type errors, such as a Python integer being used as a string "out" param.
  294.     def _CallMethodException_(self, com_object, index, info, params, exc_info):
  295.         # Later we may want to have some smart "am I debugging" flags?
  296.         # Or maybe just delegate to the actual object - it's probably got the best
  297.         # idea what to do with them!
  298.         flags, name, param_descs, ret = info
  299.         exc_typ, exc_val, exc_tb = exc_info
  300.         # use the xpt module to get a better repr for the method.
  301.         # But if we fail, ignore it!
  302.         try:
  303.             import xpcom.xpt
  304.             m = xpcom.xpt.Method(info, index, None)
  305.             func_repr = m.Describe().lstrip()
  306.         except:
  307.             func_repr = "%s(%r)" % (name, param_descs)
  308.         return self._doHandleException(func_repr, exc_info)
  309.  
  310.     # Called whenever a gateway fails due to anything other than _CallMethod_.
  311.     # Really only used for the component loader etc objects, so most
  312.     # users should never see exceptions triggered here.
  313.     def _GatewayException_(self, name, exc_info):
  314.         return self._doHandleException(name, exc_info)
  315.  
  316. _supports_primitives_data_ = [
  317.     ("nsISupportsCString", "__str__", str),
  318.     ("nsISupportsString", "__str__", str),
  319.     ("nsISupportsPRUint64", "__long__", long),
  320.     ("nsISupportsPRInt64", "__long__", long),
  321.     ("nsISupportsPRUint32", "__int__", int),
  322.     ("nsISupportsPRInt32", "__int__", int),
  323.     ("nsISupportsPRUint16", "__int__", int),
  324.     ("nsISupportsPRInt16", "__int__", int),
  325.     ("nsISupportsPRUint8", "__int__", int),
  326.     ("nsISupportsPRBool", "__nonzero__", operator.truth),
  327.     ("nsISupportsDouble", "__float__", float),
  328.     ("nsISupportsFloat", "__float__", float),
  329. ]
  330.  
  331. # Support for the nsISupports primitives:
  332. class SupportsPrimitive:
  333.     _com_interfaces_ = ["nsISupports"]
  334.     def __init__(self, iid, base_ob, attr_name, converter):
  335.         self.iid = iid
  336.         self.base_ob = base_ob
  337.         self.attr_name = attr_name
  338.         self.converter = converter
  339.     def _query_interface_(self, iid):
  340.         if iid == self.iid:
  341.             return 1
  342.         return None
  343.     def get_data(self):
  344.         method = getattr(self.base_ob, self.attr_name)
  345.         val = method()
  346.         return self.converter(val)
  347.     def set_data(self, val):
  348.         raise ServerException(nsError.NS_ERROR_NOT_IMPLEMENTED)
  349.     def toString(self):
  350.         return str(self.get_data())
  351.  
  352. def _shutdown():
  353.     class_info_cache.clear()
  354.